package com.M10.BE.inventory;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.M10.BE.R;
import com.M10.BE.adapter.NullStringToEmptyAdapterFactory;
import com.bigkoo.pickerview.TimePickerView;
import com.fn.useries.UHFApplication;
import com.fn.useries.model.Inve;
import com.fn.useries.model.Org;
import com.fn.useries.model.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.wx.wheelview.widget.WheelViewDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author LuoDaHai
 * @decs 线上盘点
 * @time 2018/3/7   13:05
 */
public class OnlineInActivity extends Activity {

    @BindView(R.id.tv_online_back)
    TextView tvOnlineBack;
    @BindView(R.id.tv_online_start_date)
    TextView tvOnlineStartDate;
    @BindView(R.id.tv_online_end_date)
    TextView tvOnlineEndDate;
    @BindView(R.id.btn_online_postion)
    Button btnOnlinePostion;
    @BindView(R.id.btn_online_type)
    Button btnOnlineType;
    @BindView(R.id.btn_online_cancel)
    Button btnOnlineCancel;
    @BindView(R.id.btn_online_enter)
    Button btnOnlineEnter;
    @BindView(R.id.tv_online_postion)
    TextView tvOnlinePostion;
    @BindView(R.id.tv_online_type)
    TextView tvOnlineType;
    @BindView(R.id.ll_online_pro)
    LinearLayout llp;
    @BindView(R.id.fl_online_pro)
    FrameLayout flp;
    private Gson gson;
    private ArrayList<Type> types = new ArrayList<>();
    private ArrayList<Org> orgs = new ArrayList<>();
    private ArrayList<String> strTypes = new ArrayList<>();
    private ArrayList<String> strOrgs = new ArrayList<>();
    private ArrayList<Inve> inves = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_online_in);
        ButterKnife.bind(this);
        gson = new GsonBuilder().serializeNulls().
                registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
        getType();
        llp.setVisibility(View.VISIBLE);
        flp.setAlpha((float) 0.7);
    }

    @OnClick({R.id.tv_online_back, R.id.tv_online_start_date, R.id.tv_online_end_date, R.id.btn_online_postion, R.id.btn_online_type, R.id.btn_online_cancel, R.id.btn_online_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_online_back:
                finish();
                break;

            case R.id.tv_online_start_date:
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        tvOnlineStartDate.setText(getTime(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.tv_online_end_date:
                TimePickerView pvTime1 = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        tvOnlineEndDate.setText(getTime(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .build();
                pvTime1.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime1.show();
                break;
            case R.id.btn_online_postion:
                if (strOrgs.size() > 0) {
                    WheelViewDialog dialog = new WheelViewDialog(this);
                    dialog.setTitle("部门选择")
                            .setItems(strOrgs)
                            .setButtonText("确定")
                            .setDialogStyle(Color
                                    .parseColor("#2395f0"))
                            .setCount(5)
                            .setOnDialogItemClickListener(new WheelViewDialog.OnDialogItemClickListener() {
                                @Override
                                public void onItemClick(int position, String s) {
                                    tvOnlinePostion.setText(orgs.get(position).getName());
                                }
                            }).show();
                } else {
                    Toast.makeText(OnlineInActivity.this,
                            "获取使用部门失败！请联系管理人员", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_online_type:
                if (strTypes.size() > 0) {
                    WheelViewDialog dialog1 = new WheelViewDialog(this);
                    dialog1.setTitle("分类选择")
                            .setItems(strTypes)
                            .setButtonText("确定")
                            .setDialogStyle(Color
                                    .parseColor("#2395f0"))
                            .setCount(5)
                            .setOnDialogItemClickListener(new WheelViewDialog.OnDialogItemClickListener() {
                                @Override
                                public void onItemClick(int position, String s) {
                                    tvOnlineType.setText(types.get(position).getName());
                                }
                            }).show();
                } else {
                    Toast.makeText(OnlineInActivity.this,
                            "获取资产分类失败！请联系管理人员", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_online_cancel:
                finish();
                break;
            case R.id.btn_online_enter:
                /**
                 * startDate	开始时间
                 * endDate		结束时间
                 * useOrg		使用部门
                 * type		资产分类
                 */
                getInventoryList(tvOnlineStartDate.getText().toString()
                        , tvOnlineEndDate.getText().toString()
                        , tvOnlinePostion.getText().toString()
                        , tvOnlineType.getText().toString());
                break;
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private void getType() {
        types.clear();
        strTypes.clear();
        OkGo.<String>get(UHFApplication.BASE_HEAD + "asset/getType")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            getOrg();
                            JSONObject object = new JSONObject(response.body());
                            if (object.optInt("status") == 1) {
                                JSONArray list = object.optJSONArray("typeList");
                                if (list.length() > 0) {
                                    for (int i = 0; i < list.length(); i++) {
                                        types.add(gson.fromJson(list.optJSONObject(i)
                                                .toString(), Type.class));
                                        strTypes.add(list.optJSONObject(i).optString("name"));
                                    }
                                } else {
                                    Toast.makeText(OnlineInActivity.this,
                                            "系统尚未配置资产分类！", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(OnlineInActivity.this,
                                        "获取资产分类失败！", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(OnlineInActivity.this,
                                "获取资产分类失败！", Toast.LENGTH_SHORT).show();
                        getOrg();
                    }
                });
    }

    private void getOrg() {
        orgs.clear();
        strOrgs.clear();
        OkGo.<String>get(UHFApplication.BASE_HEAD + "asset/getOrgList")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            llp.setVisibility(View.GONE);
                            flp.setAlpha(1);
//                            llp.setVisibility(View.GONE);
                            JSONObject object = new JSONObject(response.body());
                            if (object.optInt("status") == 1) {
                                JSONArray list = object.optJSONArray("orgList");
                                if (list.length() > 0) {
                                    for (int i = 0; i < list.length(); i++) {
                                        orgs.add(gson.fromJson(list.optJSONObject(i)
                                                .toString(), Org.class));
                                        strOrgs.add(list.optJSONObject(i).optString("name"));
                                    }
                                } else {
                                    Toast.makeText(OnlineInActivity.this,
                                            "系统尚未配置使用部门！", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(OnlineInActivity.this,
                                        "获取使用部门失败！", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(OnlineInActivity.this,
                                "获取使用部门失败！", Toast.LENGTH_SHORT).show();
                        llp.setVisibility(View.GONE);
                        flp.setAlpha(1);
                    }
                });
    }

    /**
     * startDate	开始时间
     * endDate		结束时间
     * useOrg		使用部门
     * type		资产分类
     */
    private void getInventoryList(
            String startDate,
            String endDate,
            String useOrg,
            String type
    ) {
        llp.setVisibility(View.VISIBLE);
        flp.setAlpha((float) 0.7);
        inves.clear();
        OkGo.<String>get(UHFApplication.BASE_HEAD + "asset/getInventoryList")
                .tag(this)
                .params("startDate", startDate)
                .params("endDate", endDate)
                .params("useOrg", useOrg)
                .params("type", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            llp.setVisibility(View.GONE);
                            flp.setAlpha(1);
                            JSONObject object = new JSONObject(response.body());
                            if (object.optInt("status") == 1) {
                                JSONArray list = object.optJSONArray("list");
                                if (list.length() > 0) {
                                    for (int i = 0; i < list.length(); i++) {
                                        inves.add(gson.fromJson(list.optJSONObject(i)
                                                .toString(), Inve.class));
                                    }
                                    Intent intent = new Intent();
                                    intent.setClass(OnlineInActivity.this, InveActivity.class);
                                    intent.putExtra("inves", (Serializable) inves);
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(OnlineInActivity.this,
                                            "查无数据！", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(OnlineInActivity.this,
                                        "查询失败！", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            llp.setVisibility(View.GONE);
                            flp.setAlpha(1);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(OnlineInActivity.this,
                                "查询失败！", Toast.LENGTH_SHORT).show();
                        llp.setVisibility(View.GONE);
                        flp.setAlpha(1);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
